package cn.b.sky.mes.qm.controller;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.b.sky.mes.qm.model.Defect;
import cn.b.sky.mes.qm.model.DefectAttributeValue;
import cn.b.sky.mes.qm.model.DefectTopN;
import cn.b.sky.mes.qm.model.InspectRecord;
import cn.b.sky.mes.qm.model.condition.InspectRecordCondition;
import cn.b.sky.mes.qm.service.DefectAttributeService;
import cn.b.sky.mes.qm.service.DefectService;
import cn.b.sky.mes.qm.service.InspectRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.b.sky.mes.cm.model.WorkCenter;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.file.ExcelUtil;
import cn.b.sky.common.utils.DateUtils;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;
import cn.b.sky.mes.pp.model.OrderType;
import cn.b.sky.mes.pp.model.ProductionControl;
import cn.b.sky.mes.pp.service.OrderTypeService;
import cn.b.sky.mes.pp.service.ProductionControlService;
import cn.b.sky.mes.qm.constants.QmConstant;

/**
 * 
 * <strong>Title : InspectRecordController.java<br>
 * </strong> <strong>Package : cn.b.sky.mes.qm.controller<br>
 * </strong> <strong>Description : </strong>过程检验控制器<br>
 * <strong>Create on : 2015-12-18 下午5:05:12<br>
 * </strong>
 * <p>
 * 
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 *          <strong>修改历史:</strong><br>
 *          修改人 | 修改日期 | 修改描述<br>
 *          -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/inspectRecord/*")
@Slf4j
public class InspectRecordController extends SecurityController {
  @Resource
  private InspectRecordService inspectRecordService;

  @Resource
  private DefectService defectService;

  @Resource
  private DefectAttributeService defectAttributeService;

  @Resource
  private OrderTypeService orderTypeService;

  @Resource
  private ProductionControlService productionControlService;

  @Resource
  ECodeService eCodeService;

  /**
   * 
   * <strong>Title : inspectRecordList<br>
   * </strong> <strong>Description : </strong>过程检验列表<br>
   * <strong>Create on : 2015-12-18 下午5:07:06<br>
   * </strong>
   * <p>
   * 
   * @return String
   * @throws
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   *          <strong>修改历史:</strong><br>
   *          修改人 | 修改日期 | 修改描述<br>
   *          -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("inspectRecordList")
  public String inspectRecordList(@ModelAttribute("condition") InspectRecordCondition condition, String navTabId,
                                  Model model, HttpSession session) {
    try {
      condition.setSiteCode(this.getSiteCode());
      List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
      int count = inspectRecordService.getInspectRecordCountByCondition(condition);
      condition.setData(inspectRecords);
      condition.setTotalCount(count);
      session.setAttribute(QmConstant.INSPECTRECORD_CONDITION, condition);
      //订单类型
      model.addAttribute("page", condition);
      model.addAttribute(NAVTABID, navTabId);
    } catch (Exception e) {
      log.debug("{}", e);
    }
    return "qm/inspectRecord/inspectRecord_list";
  }

  /**
   * 
   * <strong>Title : productOrderInspect<br></strong>
   * <strong>Description : </strong>订单档案过程检验数据<br> 
   * <strong>Create on : 2016-1-13 上午11:45:00<br></strong>
   * <p>
   * @param condition
   * @param navTabId
   * @param model
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("productOrderInspect")
  public String productOrderInspect(@ModelAttribute("condition") InspectRecordCondition condition, String navTabId,
      Model model) {
    if (condition != null && !StringUtils.isBlank(condition.getProductionNum())) {
      // -1表示全部
      if ("-1".equals(condition.getWorkCenterCodeStr())) {
        condition.setWorkCenterCodeStr(null);
      }
      condition.setSiteCode(this.getSiteCode());
      List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
      int count = inspectRecordService.getInspectRecordCountByCondition(condition);
      List<WorkCenter> workCenters = inspectRecordService.getInspectRecordWorkCenters(condition);
      //填充缺陷
      for (InspectRecord inspectRecord : inspectRecords) {
        inspectRecord.setDefect(defectService.getDefect(inspectRecord.getDefectCode(), this.getSiteCode()));
      }
      model.addAttribute("workCenters", workCenters);
      condition.setData(inspectRecords);
      condition.setTotalCount(count);
      model.addAttribute("page", condition);
    }
    return "pp/archives/productOrder_inspect";
  }

  /**
   * 
   * <strong>Title : inspectNoWorkCenter<br></strong>
   * <strong>Description : </strong>订单档案，过程检验局部刷新<br> 
   * <strong>Create on : 2016-1-13 下午5:04:07<br></strong>
   * <p>
   * @param condition
   * @param navTabId
   * @param model
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("inspectNoWorkCenter")
  public String inspectNoWorkCenter(@ModelAttribute("condition") InspectRecordCondition condition, String navTabId,
      Model model) {
    if (condition != null && !StringUtils.isBlank(condition.getProductionNum())) {
      // -1表示全部
      if ("-1".equals(condition.getWorkCenterCodeStr())) {
        condition.setWorkCenterCodeStr(null);
      }
      condition.setSiteCode(this.getSiteCode());
      List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
      int count = inspectRecordService.getInspectRecordCountByCondition(condition);
      //填充缺陷
      for (InspectRecord inspectRecord : inspectRecords) {
        inspectRecord.setDefect(defectService.getDefect(inspectRecord.getDefectCode(), this.getSiteCode()));
      }
      condition.setData(inspectRecords);
      condition.setTotalCount(count);
      model.addAttribute("page", condition);
    }
    return "pp/archives/inspectNoWorkCenter";
  }

  /**
   * 
   * <strong>Title : productionControlInspect<br></strong>
   * <strong>Description : </strong>生产管理号档案 过程检验<br> 
   * <strong>Create on : 2016-5-24 下午5:05:40<br></strong>
   * <p>
   * @param condition
   * @param navTabId
   * @param model
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("productionControlInspect")
  public String productionControlInspect(@ModelAttribute("condition") InspectRecordCondition condition,
      String navTabId, Model model) {
    if (condition != null && !StringUtils.isBlank(condition.getControlNum())) {

      condition.setSiteCode(this.getSiteCode());
      List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
      int count = inspectRecordService.getInspectRecordCountByCondition(condition);
      //填充缺陷
      for (InspectRecord inspectRecord : inspectRecords) {
        inspectRecord.setDefect(defectService.getDefect(inspectRecord.getDefectCode(), this.getSiteCode()));
      }
      condition.setData(inspectRecords);
      condition.setTotalCount(count);
      model.addAttribute("page", condition);
    }
    return "pp/productionControlArchives/productOrder_inspect";
  }

  @RequestMapping("controlInspectSearch")
  public String controlInspectSearch(@ModelAttribute("condition") InspectRecordCondition condition, String navTabId,
      Model model) {
    if (condition != null && !StringUtils.isBlank(condition.getControlNum())) {

      condition.setSiteCode(this.getSiteCode());
      List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
      int count = inspectRecordService.getInspectRecordCountByCondition(condition);
      //填充缺陷
      for (InspectRecord inspectRecord : inspectRecords) {
        inspectRecord.setDefect(defectService.getDefect(inspectRecord.getDefectCode(), this.getSiteCode()));
      }
      condition.setData(inspectRecords);
      condition.setTotalCount(count);
      model.addAttribute("page", condition);
    }
    return "pp/productionControlArchives/inspectNoWorkCenter";
  }

  /**
   * 
   * <strong>Title : viewInspectRecord<br>
   * </strong> <strong>Description : </strong>查看控制器<br>
   * <strong>Create on : 2015-12-18 下午5:14:17<br>
   * </strong>
   * <p>
   * 
   * @param model
   * @param id
   * @return String
   * @throws
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   *          <strong>修改历史:</strong><br>
   *          修改人 | 修改日期 | 修改描述<br>
   *          -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("viewInspectRecord")
  public String viewInspectRecord(Model model, Long id) {
    if (null == id) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    InspectRecord inspectRecord = inspectRecordService.getInspectRecordById(id);
    inspectRecord.setAttachments(inspectRecordService.getInspectRecordAttachment(inspectRecord.getId()));
    Defect defect = defectService.getDefect(inspectRecord.getDefectCode(), this.getSiteCode());
    List<DefectAttributeValue> datts = defectAttributeService.getDefectAttributeValuesForGraph(
        inspectRecord.getDefectCode(), this.getSiteCode());
    defect.setDefectAttributeValue(datts);
    ProductionControl orderDetail = productionControlService.selectProductionControl(getSiteCode(),
        inspectRecord.getProductionControlNum());
    model.addAttribute("inspectRecord", inspectRecord);
    model.addAttribute("defect", defect);
    model.addAttribute("orderDetail", orderDetail);
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.PRODUCTIONCONTROL_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("orderStatusECode", ecode);
    return "qm/inspectRecord/inspectRecord_view";
  }

  @RequestMapping("exportToExcel")
  public void exportToExcel(String navTabId, Model model, HttpSession session, HttpServletResponse response) {
    InspectRecordCondition condition = null;
    if (session.getAttribute(QmConstant.INSPECTRECORD_CONDITION) != null) {
      condition = (InspectRecordCondition) session.getAttribute(QmConstant.INSPECTRECORD_CONDITION);
    }
    if (null == condition) {
      condition = new InspectRecordCondition();
    }
    condition.setSiteCode(this.getSiteCode());
    //查询全部
    condition.setPageNum(1);
    condition.setEndRow(-1);
    List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
    String language = SecurityContextUtil.getLanguageCode();
    if (inspectRecords != null && inspectRecords.size() > 0) {
      Map<String, String> map = new LinkedHashMap<String, String>();
      map.put("productionControlNum", getImeViewMessageI18n(language, "productionControlNum.C"));
      map.put("ProductionOrderNum", getImeViewMessageI18n(language, "productionOrderNum.C"));
      map.put("orderTypeText", getImeViewMessageI18n(language, "orderType.C"));
      map.put("materialCode", getImeViewMessageI18n(language, "materialCode.C"));
      map.put("materialText", getImeViewMessageI18n(language, "materialText.C"));
      map.put("productionlotNum", getImeViewMessageI18n(language, "productionlotNum.C"));
      map.put("createUser", getImeViewMessageI18n(language, "inspectUser.C"));
      map.put("createDateTime", getImeViewMessageI18n(language, "inspectDateTime.C"));
      map.put("workcenterCode", getImeViewMessageI18n(language, "workCenterCode.C"));
      map.put("workcenterText", getImeViewMessageI18n(language, "workCenterText.C"));
      map.put("workunitCode", getImeViewMessageI18n(language, "workUnitCode.C"));
      map.put("workunitText", getImeViewMessageI18n(language, "workUnitText.C"));
      map.put("operationCode", getImeViewMessageI18n(language, "qmOperation.C,code.C"));
      map.put("operationText", getImeViewMessageI18n(language, "qmOperation.C,name.C"));
      map.put("defectCode", getImeViewMessageI18n(language, "defectCode.C"));
      map.put("defectText", getImeViewMessageI18n(language, "defectText.C"));
      map.put("quantity", getImeViewMessageI18n(language, "defectDefine.C,quantity.C"));
      map.put("attachmentCount", getImeViewMessageI18n(language, "attachment.C,quantity.C"));
      map.put("customer", getImeViewMessageI18n(language, "customer.C"));
      map.put("customerOrder", getImeViewMessageI18n(language, "customerOrder.C"));
      map.put("priority", getImeViewMessageI18n(language, "priority.C"));

      try {
        ExcelUtil.exportToExcel(response, "过程检验台账", map, inspectRecords);
      } catch (IOException e) {
        log.error("{}", e);
      }

    }
  }

  @RequestMapping("defectTopModel")
  public String defectTopModel(String navTabId, Model model, HttpSession session) {
    InspectRecordCondition condition = new InspectRecordCondition();
    condition.setSiteCode(this.getSiteCode());
    DateUtils dateUtils = DateUtils.getDateUtils(DateUtils.YYYY_MM_DD);
    //默认前一天的时间
    String nowStr = dateUtils.format(dateUtils.operationDay(new Date(), -1));
    condition.setMinCreateDateTime(nowStr + " 00:00:00");
    condition.setMaxCreateDateTime(nowStr + " 23:59:59");
    condition.setNumPerPage(5);
    List<DefectTopN> topns = inspectRecordService.getDefectTopNData(condition);
    //订单状态
    List<OrderType> orderTypes = orderTypeService.getAllUnlockedOrderTypes(this.getSiteCode());
    model.addAttribute("orderTypes", orderTypes);
    model.addAttribute("condition", condition);
    model.addAttribute("defectTopN", topns);
    session.setAttribute(QmConstant.DEFECTTOP_CONDITION, condition);
    return "qm/qualityReport/defect_topn";
  }

  @RequestMapping("defectTopModelSearch")
  public String defectTopModelSearch(@ModelAttribute("condition") InspectRecordCondition condition, String navTabId,
      Model model, HttpSession session) {
    condition.setSiteCode(this.getSiteCode());
    if (condition.getNumPerPage() > 10) {
      condition.setNumPerPage(10);
    }
    List<DefectTopN> topns = inspectRecordService.getDefectTopNData(condition);
    model.addAttribute("defectTopN", topns);
    //订单状态
    List<OrderType> orderTypes = orderTypeService.getAllUnlockedOrderTypes(this.getSiteCode());
    model.addAttribute("orderTypes", orderTypes);
    session.setAttribute(QmConstant.DEFECTTOP_CONDITION, condition);
    return "qm/qualityReport/defect_topn";
  }

  @RequestMapping("defectTopDetail")
  public String defectTopDetail(String defectCode, Integer numPerPage, Integer pageNum, String navTabId, Model model,
      HttpSession session) {
    InspectRecordCondition condition = new InspectRecordCondition();
    if (session.getAttribute(QmConstant.DEFECTTOP_CONDITION) != null) {
      condition = (InspectRecordCondition) session.getAttribute(QmConstant.DEFECTTOP_CONDITION);
    }
    if (defectCode.indexOf(QmConstant.TOPN_OTHER) != -1) {
      condition.setDefectCode(null);
      condition.setOtherDefectCode(defectCode);
    } else if (QmConstant.TOPN_TOTAL.equals(defectCode)) {
      condition.setDefectCode(null);
      condition.setOtherDefectCode(null);
    } else {
      condition.setDefectCode(defectCode);
      condition.setOtherDefectCode(null);
    }
    condition.setSiteCode(this.getSiteCode());
    //复原分页条目
    condition.setNumPerPage(20);
    //分页
    if (numPerPage != null) {
      condition.setNumPerPage(numPerPage);
    }
    condition.setPageNum(pageNum == null ? 1 : pageNum);
    List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
    int count = inspectRecordService.getInspectRecordCountByCondition(condition);
    condition.setData(inspectRecords);
    condition.setTotalCount(count);

    model.addAttribute("page", condition);
    model.addAttribute(NAVTABID, navTabId);
    return "qm/inspectRecord/defectTopDetail";
  }

  @RequestMapping("defectExportToExcel")
  public void defectExportToExcel(String navTabId, Model model, String defectCode, HttpSession session,
      HttpServletResponse response) {
    InspectRecordCondition condition = null;
    if (session.getAttribute(QmConstant.DEFECTTOP_CONDITION) != null) {
      condition = (InspectRecordCondition) session.getAttribute(QmConstant.DEFECTTOP_CONDITION);
    }
    if (condition == null) {
      condition = new InspectRecordCondition();
    }
    //topN详情导出时候的条件
    if (defectCode.indexOf(QmConstant.TOPN_OTHER) != -1) {
      condition.setDefectCode(null);
      condition.setOtherDefectCode(defectCode);
    } else if (QmConstant.TOPN_TOTAL.equals(defectCode)) {
      condition.setDefectCode(null);
      condition.setOtherDefectCode(null);
    } else {
      condition.setDefectCode(defectCode);
      condition.setOtherDefectCode(null);
    }
    condition.setSiteCode(this.getSiteCode());
    //查询全部
    condition.setPageNum(1);
    condition.setEndRow(-1);
    List<InspectRecord> inspectRecords = inspectRecordService.getInspectRecordsByCondition(condition);
    String language = SecurityContextUtil.getLanguageCode();
    if (inspectRecords != null && inspectRecords.size() > 0) {
      Map<String, String> map = new LinkedHashMap<String, String>();
      map.put("ProductionOrderNum", getImeViewMessageI18n(language, "productionOrderNum.C"));
      map.put("materialCode", getImeViewMessageI18n(language, "materialCode.C"));
      map.put("materialText", getImeViewMessageI18n(language, "materialText.C"));
      map.put("productionlotNum", getImeViewMessageI18n(language, "productionlotNum.C"));
      map.put("createUser", getImeViewMessageI18n(language, "inspectUser.C"));
      map.put("createDateTime", getImeViewMessageI18n(language, "inspectDateTime.C"));
      map.put("workcenterCode", getImeViewMessageI18n(language, "workCenterCode.C"));
      map.put("workcenterText", getImeViewMessageI18n(language, "workCenterText.C"));
      map.put("workunitCode", getImeViewMessageI18n(language, "workUnitCode.C"));
      map.put("workunitText", getImeViewMessageI18n(language, "workUnitText.C"));
      map.put("quantity", getImeViewMessageI18n(language, "defectDefine.C,quantity.C"));
      map.put("attachmentCount", getImeViewMessageI18n(language, "attachment.C,quantity.C"));

      try {
        ExcelUtil.exportToExcel(response, "过程检验台账", map, inspectRecords);
      } catch (IOException e) {
        log.error("{}", e);
      }

    }
  }

}
